<template>
  <div id="product">
    <Header></Header>
   <div id="productAll">
     <div class="pro-left">
       <div @mouseover="magnifierMin=true"    @mouseout="magnifierMin=false" class="wxz">
         <div class="mask" @mousemove.capture="magnifierMove" style="cursor: move" @mousewheel.prevent></div>
         <div class="magnifierMin" v-show="magnifierMin" :style="{top:magnifierY+'px',left: magnifierX+'px'}"></div>
         <img :src="product_obj.mainimage" alt="" style="background-color:#F7F7F7;">
       </div>
       <div class="magnifierMax" v-show="magnifierMin" :style="{backgroundImage: 'url('+product_obj.mainimage+')',backgroundPositionX:-magnifierX*2.5+'px',backgroundPositionY:-magnifierY*2.5+'px'}"></div>
       <div class="swiper">
         <span @click="buttonLeft" v-if="lenghtSub>5">&lt;</span>
         <div>
           <div class="wrapper"  :style="{left:location+'px'}" >
             <img :src="item" alt="" v-for="item in product_obj.subimages" @mouseover="imgMover(item)" class="hand">
           </div>
         </div>
         <span @click="buttonRight" v-if="lenghtSub>5">&gt;</span>
       </div>
     </div>
     <div class="pro-right">
       <h3 v-html="product_obj.title"></h3>
       <p v-if="product_obj.subtitle!=''" v-html="product_obj.subtitle" style="color: red;margin-bottom: 10px"></p>
       <div class="goods">
         <p v-html="product_obj.priceLine==product_obj.price?'价格':'活动价'"></p>
         <p><span>￥</span><span v-html="product_obj.price"></span></p>
         <p v-if="product_obj.priceLine!==product_obj.price"><span>￥</span><span v-html="product_obj.priceLine"></span></p>
         <span>库存 <span>{{product_obj.stock}}</span></span><span>销量 <span>{{product_obj.salesVolume}}</span></span>
       </div>
       <p style="margin-top: 15px;color: #999">单个商品一次限购十件</p>
       <div class="dotted"></div>
       <div class="attr gift hand">
         <span>赠品</span>
         <img :src="date.giveImg" alt="">
         <p>{{date.giveName}} <span style="color: #666">x1</span></p>
       </div>
       <div class="attr color">
         <span>颜色</span>
         <div v-if="product_obj.isColor!=0">
           <div class="hand" :class="product_obj.isColor==1?'active':''" @click="jump(product_obj.isColor==2,product_obj.otherColorsID)">{{product_obj.isColor==1?product_obj.defaultColor:product_obj.otherColors}}</div>
           <div class="hand" :class="product_obj.isColor==2?'active':''" @click="jump(product_obj.isColor==1,product_obj.otherColorsID)">{{product_obj.isColor==2?product_obj.defaultColor:product_obj.otherColors}}</div>
         </div>
         <div v-if="product_obj.isColor==0">
           <div class="hand" :class="'active'" ><span style="background-color:#000;"></span>默认</div>
         </div>
       </div>
       <div class="attr quantity">
         <span>数量</span>
         <div class="inp hand">
           <input type="button" class="hand" value="-" @click="date.quantity=reduce(date.quantity)">
           <input type="text" class="hand" v-model.trim="date.quantity" @input="date.quantity=changeQuantity(date.quantity)">
           <input type="button" :disabled="quantityFlag" :plain="true" class="hand" value="+" @click="date.quantity=increase(date.quantity,$event)">
         </div>
       </div>
       <div class="attr-bnt" v-if="stock">
<!--         <button @click="addCart" class="hand">加入购物车</button>-->
         <el-button button-size="small" text @click="open">加入购物车</el-button>

         <button @click="purchase" class="hand">立即购买</button>
          <span class="iconfont icon-aixin-kuai hand" :plain="true" @click="collect"   :class="userCollect?'active':''" ></span>
       </div>
       <div class="attr-bnt" v-else>
         <button @click="notice" class="hand">到货通知</button>
       </div>
       <p>温馨提示： 支持7天无理由退货(拆封后不支持)</p>
<!--       <div><span>库存</span><span>销量</span></div>-->
     </div>
   </div>
    <div id="recommend">
      <h4>推荐商品</h4>
      <div class="goods-list">
        <div v-for="item in recommend" class="hand" style="background-color:#F7F7F7;" :key="item.id">
          <router-link :to="{name:'Product',query:{id:item.id}}" style="text-decoration: none">
            <img :src="item.mainimage" alt="" style="background-color:rgba(00,00,00,0.05);">
            <div>
              <p>{{item.title}}</p>
              <p>￥{{item.price}}</p>
            </div>
          </router-link>
        </div>
      </div>
    </div>
    <Footer></Footer>
  </div>
</template>

<script setup>
// 引入公共部分
import Header from "../components/Header.vue";
import Footer from "../components/Footer.vue";
import '../assets/font/product/iconfont.css';
import {ref, onMounted, getCurrentInstance, nextTick, watch} from "vue";
import {useRouter,useRoute} from "vue-router"

import { ElMessage, ElMessageBox } from 'element-plus'

const { proxy } = getCurrentInstance();

//收藏
let userLocalStorage=ref(localStorage['token']);
let userCollect=ref(false);
let userFlag=true;
let timerCollect;
//浏览历史
let  history=(val)=>{
  let date=new Date().toLocaleString();
  let arr=localStorage.getItem("history")?localStorage.getItem("history"):[];
  if(arr.length!=0){ //有数据才转
    arr=JSON.parse(arr);//
  }
  let obj={
    val:val,
    date:date
  }
  if (arr.length!==0){
    let sum=true;
    for (let i=0;i<arr.length;i++){
      if (arr[i].val.id===val.id){
        sum=false;
        arr[i].val=val;
        arr[i].date=date;
      }
    }
    if (sum){
      arr.push(obj);
    }
  }else {
    arr.push(obj);
  }
  arr=JSON.stringify(arr);
  localStorage.setItem("history",arr);
}
let collect=()=>{
  if (userLocalStorage.value!=undefined){
    if (userFlag){
      userFlag=false;
      if (!userCollect.value){
        ElMessage(
            {
              message:'加入收藏成功',
              type:'success'
            }
        )
      }else {
        ElMessage(
            {
              message:'取消收藏成功',
              type:'success'
            }
        )
      }
      userCollect.value=!userCollect.value;
      timerCollect=setTimeout(()=>{
        userFlag=true;
      },1000)
      let obj={
        isCollect:userCollect.value,
        id,
      }
      // 点击收藏发送请求
      proxy.$post('/api/collect/changeState',obj).then(data=>{
        console.log(data.msg);
      })
    }else {
      clearInterval(timerCollect);
      timerCollect=setTimeout(()=>{
        userFlag=true;
      },1000)
      ElMessage({
        message: '操作频繁',
        type: 'warning',
      })
    }
    userFlag=false;
  }else {
    ElMessage({
      message: '未登录，请先登录',
      type: 'warning',
    })
    setTimeout(()=>{
      router.push('/login?type=login');
    },1500)
  }
}
//加入购物车
const open = () => {
  if (localStorage['token']){
    let obj={};
    obj.id=id;
    obj.quantity=date.value.quantity;
    proxy.$post('/api/cart/addCart',obj).then(data=>{
      if (data.code===200){
        ElMessageBox.confirm(
            '已成功加入购物车！',
            {
              confirmButtonText: '去购物车结算',
              cancelButtonText: '继续购物',
              type: 'success',
              center: true,
            }
        )
            .then(() => {
              // 去购物车结算
              router.push('/cart');
            })
            .catch(() => {
              // 继续购物
            })
      }else {
        ElMessage({
          message: '单个商品限购十件',
          type: 'warning',
        })
      }
    }).catch((err) => {
      console.log(err);
    });
  }else {
    ElMessage({
      message: '未登录，正在跳转...',
      type: 'warning',
    })
    setTimeout(()=>{
      router.push('/login?type=login');
    },1500)
  }
}

// 获取query参数id
const router = useRouter();
const route = useRoute();
let id = router.currentRoute.value.query.id;
// console.log(id);

// 刷新页面
watch(route,(newV)=>{
  // console.log(newV.query.id)
  router.go(0)
})

let product_obj = ref({})
let recommend=ref()
let lenghtSub=ref();
// 判断是否有库存
let stock = ref(true);
// 挂载后请求数据
// let isCollection=ref(null);
onMounted(()=>{
  proxy.$post("/api/data/product",{id}).then((data)=>{
    if (data[1]!=null){
      userCollect.value=Boolean(data[1].state);
    }
    history(data[0]);
    // if (data[0]==null){
    //   router.push("/nofind")
    // }
    // console.log(data.stock);
    product_obj.value = data[0];
    product_obj.value.subimages=product_obj.value.subimages.split(",");
    // console.log(product_obj.value);
    lenghtSub.value=product_obj.value.subimages.length;
    if (data[0].stock===0){
      stock.value = false;
    }
  }).catch(()=>{
    router.push("/nofind")
  })
  // 获取推荐商品的后端数据
  proxy.$get("/api/data/recommend").then((data)=>{
    // console.log(data);
    recommend.value=data;
  })
})
const notice = ()=>{
  ElMessage({
    message: '已添加到货通知',
    type: 'success',
  })
}
//左右箭头
let location = ref(0)
let buttonLeft = ()=>{
  if (location.value<0){
    location.value+= 96;
  }
}
let buttonRight = ()=>{
  if (location.value>-960+96){
    location.value-= 96;
  }
}
//放大镜
let imgMover =(item)=>{
  product_obj.value.mainimage=item;
}
let magnifierX = ref(0);
let magnifierY = ref(0);
let magnifierMove=(e)=> {
  magnifierX.value = e.offsetX - 100;
  magnifierY.value = e.offsetY - 100;
  if (e.offsetX<100){
    magnifierX.value=0;
  }
  if (e.offsetX>497){
    magnifierX.value=397;
  }
  if (e.offsetY<100){
    magnifierY.value=0;
  }
  if (e.offsetY>500){
    magnifierY.value=400;
  }
}
let magnifierMin=ref(false);

let date = ref({
  giveName:"飞利浦充插两用护眼灯",
  giveImg:"/images/product/1.jpg",
  bgc:true,
  quantity:1,
})
//颜色跳转
let jump=(flag,index)=>{
  // location.href = '#/product?id='+index;
  if (flag===true){
    router.push('/product?id='+index);
  }
}
//数量
let sum=1,timer;
let quantityFlag=ref(false);
let reduce=(index)=>{
  quantityFlag.value=false;
  sum--;
  if (index<=1){
    index=1;
    sum=1
  }else {
    index--;
  }
  return index;
}
let increase=(index)=>{
  index++;
  sum++;
  if (sum>10){
    quantityFlag.value=true;
    ElMessage.error('最多购买十件')
  }
  if (index>=10){
    index=10;
    sum=10;
  }
  return index;
}
let changeQuantity=(index)=>{
  let val=index;
  if (val<1||isNaN(val)||val===""||val>10){
    clearInterval(timer);
    timer=null;
    timer=setTimeout(()=>{
       date.value.quantity=sum;
      quantityFlag.value=false;
      index=sum
    },1000)
  }else {
    sum=val;
    index=sum;
  }
  return index;
}

// 购买
let purchase = ()=>{
  // let obj={};
  // obj.quantity = date.value.quantity;
  // obj.id = id;
  // console.log(obj);
  if (localStorage['token']){
    product_obj.value.quantity = date.value.quantity;
    sessionStorage.setItem('order',JSON.stringify([product_obj.value]));
    router.push('/cart/order');
  }else {
    ElMessage({
      message: '未登录，正在跳转...',
      type: 'warning',
    })
    setTimeout(()=>{
      router.push('/login?type=login');
    },1500)

  }
}
</script>


<style scoped>
.goods>span {
  margin-left: 30px;
  color: rgba(126, 120, 120, 0.88);
  font-size: 18px;
}
.goods>span>span {
  font-size: 16px;
}
input:disabled {
  cursor: not-allowed;
}
.magnifierMax {
  position: fixed;
  width: 500px;
  height: 500px;
  top: 40%;
  left: 65%;
  background-color: #f4f4f4;
  transform: translate(-50%,-50%);
  overflow: hidden;
  background-size: 1500px 1500px;
}

.hand {
  cursor: pointer;
}
.mask {
  position: absolute;
 width: 597px;
  height: 600px;
  background-color: transparent;
  z-index: 10;
}
#productAll {
  width: 1200px;
  margin: 120px auto 0 ;
  height: 750px;
  /*background-color: #000;*/
  display: flex;
}
.pro-left {
  width: 597px;
  position: relative;
}
.magnifierMin {
  width: 200px;
  height: 200px;
  background-color: rgba(0,0,0,0.5);
  position: absolute;
}
.pro-left>div:nth-child(1){
  margin-bottom: 20px;
}
.pro-left>div>img {
  width: 597px;

}
.swiper {
  width: 100%;
  height: 89px;
  display: flex;
  align-items: center;
  justify-content: space-around;
}
.swiper>span {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  border: 1px solid #ccc;
  line-height: 24px;
  text-align: center;
  font-family: fangsong;
  cursor: pointer;
}
.swiper>span:hover {
  border-color: deepskyblue;
  color: deepskyblue;
}
.swiper>div {
  width: 480px;
  overflow: hidden;
  height: 89px;
  position: relative;
}
.wrapper {
  position: absolute;
  top: 0;
  left: 0;
  width: 960px;
  height: 89px;
  transition: all linear 0.3s;
  display: flex;
  overflow: hidden;
}
.wrapper>img {
  width: 85px;
  flex: none;
  margin-right: 11px;
  border-bottom: 1px solid transparent;
}
.wrapper>img:hover {
  border-bottom: 1px solid #000;
}
.pro-right {
  margin-left: 60px;
  color: #000;
}
.pro-right h3 {
  font-size: 18px;
  margin-bottom: 14px;
}
.goods {
  display: flex;
  font-size: 16px;
  align-items: end;
}
.goods p {
  margin-right: 10px;
}
.goods>p:nth-child(2){
  font-size: 20px;
}
.goods>p:nth-child(3){
  color: #ccc;
  text-decoration: line-through;
}
.dotted {
  border-top: 1px dashed #e0e0e0;
  margin: 15px auto 28px;
}
.attr {
  display: flex;
  margin-bottom: 40px;
  align-items: center;
}
.attr>span:nth-child(1){
  width: 28px;
  margin-right: 38px;
  color: #999;
  font-size: 14px;
}
.gift img {
  width: 42px;
}
.gift p {
  font-size: 14px;
  color: black;
  align-self: center;
  margin-left: 6px;
}
.gift p span {
  color: #dcdfe6;
}
.color>div {
  display: flex;
  align-items: center;
}
.color>div>div {
  width: 144px;
  height: 40px;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin: 0 20px 0 0;
  display: flex;
  justify-content: center;
  align-items: center;
}
.color>div>div>span {
  border: 1px solid #ccc;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  margin-right: 5px;
}
.color>div>div:nth-child(1) span{
  background-color: #fff;
}
.color>div>div:nth-child(2) span{
  background-color: #000;
}
.color div.active {
  border: 1px solid deepskyblue;
}
.quantity .inp {
  display: flex;
  border: 1px solid #ccc;
  border-radius: 5px;
}
.inp input {
  border: none;
  outline: none;
  background-color: transparent;
  height: 40px;
  width: 40px;
  text-align: center;
}
.inp input[type="button"] {
  font-size: 20px;
  color: #999999;
  font-family: monospace;
}
.inp:hover {
  border-color: deepskyblue;
}
.attr-bnt {
  width: 100%;
  height: 56px;
  margin-top: 80px;
  margin-bottom: 14px;
  display: flex;
}
.attr-bnt button {
  width: 200px;
  height: 56px;
  font-size: 24px;
  font-weight: 300;
  border-radius: 5px;
}
.attr-bnt button:nth-child(1){
  border: 1px solid #dcdfe6;
  background-color: transparent;
  color: #606266;
}
.attr-bnt button:nth-child(1):hover {
  border-color: deepskyblue;
  color: deepskyblue;
}
.attr-bnt button:nth-child(2){
  margin-left: 10px;
  border: 1px solid #409eff;
  background-color: #409eff;
  color: #fff;
}
.attr-bnt button:nth-child(2):hover {
  opacity: .8;
}
.pro-right>p {
  color: #dcdfe6;
}
.icon-aixin-kuai {
  margin-left: 30px;
  font-size: 38px;
  color: #999;
  line-height: 56px;
}
.icon-aixin-kuai.active {
  color: #fd0532;
}
#recommend {
  width: 100%;
  height: 435px;
  border-top: 1px solid #ececec;
  border-bottom: 1px solid #ececec;
  padding-bottom: 40px;
  color: black;
  /*background-color: #000;*/
}
#recommend h4 {
  text-align: center;
  height: 96px;
  line-height: 96px;
  font-size: 20px;
}
.goods-list {
  width: 1200px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
}
.goods-list img {
  width: 224px;
}
.goods-list>div {
  width: 224px;
  height: 325px;
  transition: all linear 0.2s;
}
.goods-list>div:hover {
  transform: translate(0,-10px);
  box-shadow: 0 0 10px #ccc;
}
.goods-list>div>a>div {
  font-size: 16px;
  width: 204px;
  height: 100px;
  padding: 10px;
}
.goods-list>div>a>div p:nth-child(1){
  height: 40px;
  margin-bottom: 14px;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}
.goods-list>div>a>div p:nth-child(2) {
  font-size: 18px;
  color: deepskyblue;
  width: 204px;
  margin: 0 auto 14px;
}
.iconfont.icon-aixin {
  font-size: 42px;
  line-height: 56px;
  margin-left: 13px;
  color: #999;
}
</style>
<style>
.el-popup-parent--hidden {
  padding: 0 !important;
}
.el-message-box__message p {
  font-size: 18px;
  padding: 10px !important;
}
.el-message-box {
  padding: 20px 0 40px;
}
.el-message-box__btns button {
  padding: 20px 30px;
  width: 164px;
}
.el-message-box__btns button span {
  font-size: 16px;
}
</style>